package com.mg.sms.dao;

import java.io.File;
import java.io.IOException;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * <p>Title: com.mg.dao.DBHelper</p>
 * <p>Description: 資料庫小幫手</p>
 * <p>Copyright: Copyright (c) 2011</p>
 * <p>Company: FreeLance</p>
 * @author Jason Huang
 * @version 1.0
 */
public class DBHelper extends SQLiteOpenHelper{
    
    public DBHelper(Context context)  {
        super(context, SMSConstant.DB_NAME, null, SMSConstant.DB_VERSION);
        createDataBase();
    }
    
    public DBHelper(Context context, String name, CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            db.execSQL(SMSConstant.CREATE_SMS_TABLE);
        } catch(SQLException ex) {
            Log.d("bear", ex.getMessage(), ex);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        try {
            db.execSQL("DROP TABLE IF EXISTS " + SMSConstant.TABLE_NAME);
            db.execSQL(SMSConstant.CREATE_SMS_TABLE);
        } catch(SQLException ex) {
            Log.d("bear", ex.getMessage(), ex);
        }
    }

    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
    }
    
    /**
     * 建立DB
     * @throws IOException
     */
    public void createDataBase() {
        boolean dbExist = checkDataBase();
        if(!dbExist) {
            File dir = new File(SMSConstant.DB_PATH);
            if(!dir.exists()) dir.mkdir();
            
            File dbf = new File(SMSConstant.DB_PATH + SMSConstant.DB_NAME);
            if(dbf.exists()) dbf.delete();
            
            SQLiteDatabase sqliteDatabase = SQLiteDatabase.openOrCreateDatabase(dbf, null);
            sqliteDatabase.close();
        }
    }
    
    /**
     * 檢查DB是否存在
     * @return
     */
    public boolean checkDataBase() {
        try {
            SQLiteDatabase sqliteDatabase = SQLiteDatabase.openDatabase(SMSConstant.DB_PATH + SMSConstant.DB_NAME, null, SQLiteDatabase.OPEN_READONLY);
            sqliteDatabase.close();
            return true;
        } catch(Exception ex) {
            return false;
        }
    }
}
